package com.nondo.rdp.finance.endpoint.api.admin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.nondo.rdp.auth.common.RoleUtils;
import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.ConvertCall;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.endpoint.model.Query;
import com.nondo.rdp.core.common.BeanUtils;
import com.nondo.rdp.core.common.StringUtils;
import com.nondo.rdp.core.common.ValidateUtil;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.domain.activity.MarketCourse;
import com.nondo.rdp.finance.domain.course.Course;
import com.nondo.rdp.finance.model.course.CourseQuery;
import com.nondo.rdp.finance.service.activity.MarketCourseService;
import com.nondo.rdp.finance.service.course.CourseService;

@RestController("apiAdminMarketCourse")
@RequestMapping("/api/admin/marketCourse")
public class MarketCourseEndpoint {
    @Autowired
    MarketCourseService marketCourseService;
    
    @Autowired
    CourseService courseService;
    
    /**
     * 查看营销课程
     * @param request
     * @param response
     * @param id
     * @return
     */
    @RequestMapping("/info/{id}")
	public View info(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("id") Long id) {
		View<MarketCourse> view = new View<MarketCourse>(20000, "获取数据成功");
		
		MarketCourse marketCourse = null;
		if (id != null) {
			marketCourse = marketCourseService.findOne(id);
		} else {
			marketCourse = new MarketCourse();
		}

		view.setData(marketCourse);
		return view;
	}
    
    /**
     * 添加营销课程
     * @param request
     * @param response
     * @param id
     * @return
     */
    @PreAuthorize("hasRole('ROLE_" + RoleUtils.ADMIN + "')")
	@RequestMapping("/add")
	public View add(HttpServletRequest request, HttpServletResponse response,
			@Validated @RequestBody MarketCourse marketCourse) {
		View view = new View(20000, "添加成功");

		if (StringUtils.isBlank(marketCourse.getCid())) {
			view.setCode(40000);
			view.setMessage("课程ID不能为空");
		} else {
			User user = UserUtils.getUser(request, response);
			String[] cids = marketCourse.getCid().split(",");
			for (String cid : cids) {
				Course course = this.courseService.findOne(Long.parseLong(cid));
				if (course == null) {
					continue;
				}
				int count = this.marketCourseService.getCountByCid(Long.parseLong(cid));
				if (count > 0) {
					continue;
				}
				marketCourse = new MarketCourse();
				if (marketCourse.getType() == null) {
					marketCourse.setType(0);
				}
				marketCourse.setUser(user);
				marketCourse.setCourse(course);
				this.marketCourseService.save(marketCourse);
			}
		}
		return view;
	}

    /**
     * 更新营销课程
     * @param request
     * @param response
     * @param id
     * @return
     */
	@PreAuthorize("hasRole('ROLE_" + RoleUtils.ADMIN + "')")
	@RequestMapping("/update")
	public View update(HttpServletRequest request,
			HttpServletResponse response,
			@Validated @RequestBody MarketCourse marketCourse, BindingResult result) {
		View view = new View(20000, "更新成功");

		if (result.hasErrors()) {
			view.setCode(40000);
			view.setMessage(ValidateUtil.first(result.getAllErrors()));
		} else {
			MarketCourse marketCourseDb = marketCourseService.findOne(marketCourse.getId());
			BeanUtils.copy(marketCourse, marketCourseDb);
			this.marketCourseService.update(marketCourseDb);
		}

		return view;
	}

    /**
     * 获取营销课程列表
     * @param request
     * @param response
     * @param query
     * @return
     */
	@PreAuthorize("hasRole('ROLE_" + RoleUtils.ADMIN + "')")
    @RequestMapping("/list")
    public View<Page> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<MarketCourse> query) {
        View<Page> view = new View(20000, "获取列表成功");

        MarketCourse marketCourse = query.getData();

        Page<MarketCourse> page = marketCourseService.findAll(new Page<MarketCourse>(query.getPage(), query.getSize()), marketCourse);

        Page<CourseQuery> resultPage = page.convertPage(new ConvertCall<MarketCourse, Page<CourseQuery>>() {

			@Override
			public Page<CourseQuery> execute(Page<MarketCourse> srcPage) {
				Page<CourseQuery> courseQueryPage = new Page<CourseQuery>(srcPage.getPageNumber(),srcPage.getPageSize(),srcPage.getTotalPages(),srcPage.getTotalElements());
				List<CourseQuery> courseQueryList = new ArrayList<CourseQuery>();
				List<MarketCourse> marketCourseList = srcPage.getContent();
				for(MarketCourse marketCourse : marketCourseList) {
					CourseQuery courseQuery = CourseQuery.covert2Bean(marketCourse.getCourse());
					courseQuery.setId(marketCourse.getId());
					courseQueryList.add(courseQuery);
				}
				courseQueryPage.setContent(courseQueryList);
				return courseQueryPage;
			}
        	
		});

        view.setData(resultPage);


        return view;
    }

    /**
     * 删除营销课程
     * @param request
     * @param response
     * @param id
     * @return
     */
    @PreAuthorize("hasRole('ROLE_" + RoleUtils.ADMIN + "')")
    @RequestMapping("/delete/{id}")
    public View delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "删除成功");

        this.marketCourseService.delete(id);

        return view;
    }
}